
package com.aspire.nm.component.cmppserver.runTime.moProcess;

import java.util.TimerTask;

import javax.annotation.Resource;

import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.aspire.nm.component.cmppserver.filter.coder.packet.CmppDeliverPacket;
import com.aspire.nm.component.cmppserver.runTime.SysRunTimeService;
import com.aspire.nm.component.cmppserver.util.LogService;


@Scope("prototype")
@Component
public class MoRetryTask extends TimerTask {
	
	@Value("${cmppserver.maxMoRetryTimes}")
	private int maxMoRetryTimes;
	
	@Resource
	private LogService logService;
	@Resource
	private SysRunTimeService sysRunTimeService;
	
	private MoSender moSender;
	private CmppDeliverPacket pk;
	public MoSender getMoSender() {
		return moSender;
	}
	public void setmOSender(MoSender moSender) {
		this.moSender = moSender;
	}
	public CmppDeliverPacket getPk() {
		return pk;
	}
	public void setPk(CmppDeliverPacket pk) {
		this.pk = pk;
	}
	
	
	
	
	private int retryTimes;
	@Override
	public void run() {
		if( ++ retryTimes <= maxMoRetryTimes){
			IoSession session = moSender.getConnection().getSession();
			if(!session.isClosing()){
				if(pk.bizParams==null){
					pk.bizParams = "retryTimes=1";
				}else{
					String s = (String)pk.bizParams;
					int i = Integer.parseInt(s.substring(s.lastIndexOf("=")+1)) + 1;
					pk.bizParams = "retryTimes="+i;
				}
				sysRunTimeService.setResendTimes(sysRunTimeService.getResendTimes()+1);
				moSender.getConnection().setResendTimes(moSender.getConnection().getResendTimes()+1);
				moSender.getConnection().getUserRunTime().setResendTimes(moSender.getConnection().getUserRunTime().getResendTimes()+1);
				logService.deliver(moSender.getConnection().getUserRunTime().getUser(), pk);
				session.write(pk);
			}else{
				cancel();
			}
		}else{
			cancel();
			moSender.getDeliveryRetryHt().remove(pk.getSequenceId());
		}
	}
}
